import { createRouter, createWebHashHistory } from 'vue-router'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/tools',
    name: 'Tools',
    component: () => import('../views/Tools.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/dashboard',
    name: 'Dashboard',
    component: () => import('../views/Dashboard.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        redirect: 'links'
      },
      {
        path: 'links',
        name: 'Links',
        component: () => import('../views/dashboard/Links.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'tags',
        name: 'Tags',
        component: () => import('../views/dashboard/Tags.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: 'files',
        name: 'Files',
        component: () => import('../views/dashboard/Files.vue'),
        meta: { requiresAuth: true, title: '文件管理' }
      }
    ]
  },
  {
    path: '/rate-limit',
    name: 'RateLimit',
    component: () => import('../views/RateLimit.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/call-limit',
    name: 'CallLimit',
    component: () => import('../views/CallLimit.vue'),
    meta: { requiresAuth: false }
  },
  {
    path: '/downloads',
    name: 'Downloads',
    component: () => import('../views/Downloads.vue'),
    meta: { title: '文件下载' ,requiresAuth: false}
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

// 修改路由守卫
router.beforeEach(async (to, from, next) => {
  const userInfo = localStorage.getItem('userInfo')
  
  if (to.meta.requiresAuth && !userInfo) {
    // 需要认证但没有用户信息，跳转到登录页
    next({ 
      path: '/login',
      query: { redirect: to.fullPath }
    })
  } else if (userInfo && (to.path === '/login' || to.path === '/register')) {
    // 已登录用户访问登录或注册页，重定向到dashboard
    next('/dashboard/links')
  } else {
    next()
  }
})

export default router 